import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { useAuth } from '@/composables/useAuth'
import { PermissionManager } from '@/composables/usePermissions'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: {
        title: '首页',
        requiresAuth: false
      }
    },
    // 登录页面
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
      meta: {
        title: '登录',
        requiresAuth: false
      }
    },
    // 注册页面
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/RegisterView.vue'),
      meta: {
        title: '注册',
        requiresAuth: false
      }
    },
    // 忘记密码页面
    {
      path: "/forget-password",
      name: "forget-password",
      component: () => import('@/views/ForgetPasswordView.vue'),
      meta: {
        title: '重置密码',
        requiresAuth: false
      }
    },
    // 教师首页
    {
      path: "/teacher-home",
      name: "teacher-home",
      component: () => import('@/views/HomeTeacher.vue'),
      meta: {
        title: '教师首页',
        requiresAuth: true,
        roles: ['teacher']
      }
    },
    // 学生首页
    {
      path: "/student-home",
      name: "student-home",
      component: () => import('@/views/HomeStudent.vue'),
      meta: {
        title: '学生首页',
        requiresAuth: true,
        roles: ['student']
      }
    },
    {
      path:"/student-chat",
      name:"student-chat",
      component: () => import('@/views/StudentChatView.vue'),
      meta: {
        title: 'AI对话'
      }
    },
    // 聊天页面
    {
      path: '/chat',
      name: 'chat',
      component: () => import('@/views/ChatView.vue'),
      meta: {
        title: 'AI 聊天',
        requiresAuth: true,
        roles: ['teacher', 'student']
      }
    },
    // 个人信息页面
    {
      path: '/personal-info',
      name: 'personal-info',
      component: () => import('@/views/PersonalInfoView.vue'),
      meta: {
        title: '个人信息',
        requiresAuth: true,
        roles: ['teacher', 'student']
      }
    },
    // 题目选择页面 - 仅教师可访问
    {
      path: '/questions',
      name: 'questions',
      component: () => import('@/views/QuestionsView.vue'),
      meta: {
        title: '题库管理',
        requiresAuth: true,
        roles: ['teacher']
      }
    },
    // 题库管理页面 - 仅教师可访问
    {
      path:'/question-repo',
      name: 'question-repo',
      component : () => import('@/views/QuestionRepoView.vue'),
    },
    // 资源管理页面
    {
      path: '/resources',
      name: 'resources',
      component: () => import('@/views/ResourcesView.vue'),
      meta: {
        title: '资源管理',
        requiresAuth: true,
        roles: ['teacher', 'student']
      }
    },
    // 资源库页面 - 仅教师可访问
    {
      path: '/resource-repo',
      name: 'resource-repo',
      component: () => import('@/views/ResourceRepoView.vue'),
    },
    // 学生考试相关页面
    {
      path: '/student-exam',
      name: 'student-exam',
      component: () => import('@/views/StudentExam.vue'),
      meta: {
        title: '学生考试',
        requiresAuth: true,
        roles: ['student']
      }
    },
    {
      path: '/student-exam-realize',
      name: 'student-exam-realize',
      component: () => import('@/views/StudentExamRealize.vue'),
      meta: {
        title: '考试进行',
        requiresAuth: true,
        roles: ['student']
      }
    },
    {
      path: '/student-exam-resource',
      name: 'student-exam-resource',
      component: () => import('@/views/StudentExamResource.vue'),
      meta: {
        title: '考试资源',
        requiresAuth: true,
        roles: ['student']
      }
    },
    // 404 页面
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/NotFound.vue'),
      meta: {
        title: '页面未找到',
        requiresAuth: false
      }
    }
  ],
})

// 路由守卫 - 权限验证和自动重定向
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title as string || '教育平台'
  
  // 获取认证状态
  const { isAuthenticated, userRole, getUserHomePage, checkAuthStatus } = useAuth()
  
  // 检查本地存储中的认证状态
  checkAuthStatus()
  
  const requiresAuth = to.meta.requiresAuth
  const allowedRoles = to.meta.roles as string[] | undefined
  
  // 如果不需要认证，直接通过
  if (!requiresAuth) {
    // 如果已登录用户访问登录页，重定向到对应主页
    if (isAuthenticated.value && (to.path === '/login' || to.path === '/register')) {
      next(getUserHomePage())
      return
    }
    next()
    return
  }
  
  // 需要认证但未登录
  if (!isAuthenticated.value) {
    next('/login')
    return
  }
  
  // 已登录，检查角色权限
  if (allowedRoles && allowedRoles.length > 0) {
    if (!userRole.value || !allowedRoles.includes(userRole.value)) {
      // 没有权限，重定向到对应主页
      next(getUserHomePage())
      return
    }
  }
  
  // 使用权限管理器进行额外检查
  const redirectPath = PermissionManager.getRedirectPath(userRole.value, to.path)
  if (redirectPath) {
    next(redirectPath)
    return
  }
  
  // 权限检查通过
  next()
})

// 全局后置守卫 - 处理页面加载完成后的逻辑
router.afterEach((to, from) => {
  // 可以在这里添加页面访问统计、用户行为分析等
  console.log(`导航到页面: ${to.path}`)
})

export default router
